package ddz.db.service;

import com.kaka.notice.Proxy;
import com.kaka.notice.annotation.Model;
import com.kaka.util.Charsets;
import com.kaka.util.StringUtils;
import ddz.constants.Crypto;
import ddz.core.TableToken;
import ddz.utils.DES;

@Model
public class TableTokenService extends Proxy {

    private final byte[] keyBytes = Crypto.PLAYING_TOKEN_DES_KEY.getBytes(Charsets.utf8);

    private TableTokenService() {
    }

    public String createToken(long deskId, int step, int nextOperateSeatIndex) {
        String token = deskId + ":" + step + ":" + nextOperateSeatIndex;
        byte[] bytes = token.getBytes(Charsets.utf8);
        bytes = DES.encrypt(bytes, keyBytes);
        token = StringUtils.encodeByteToHexString(bytes);
        return token;
    }

    public boolean validate(String token, long deskId, int step, int nextOperateSeatIndex) {
        String oldToken = createToken(deskId, step, nextOperateSeatIndex);
        if (token.equals(oldToken)) {
            return true;
        }
        return false;
    }

    public TableToken parseToken(String token) {
        if (!StringUtils.isNotEmpty(token)) return new TableToken(0L, 0, 0);
        byte[] bytes = StringUtils.decodeHexToByte(token);
        bytes = DES.decrypt(bytes, keyBytes);
        if (bytes == null) return new TableToken(0L, 0, 0);
        token = new String(bytes, Charsets.utf8);
        String[] parts = token.split(":");
        long deskId = Long.parseLong(parts[0]);
        int step = Integer.parseInt(parts[1]);
        int nextOperateSeatIndex = Integer.parseInt(parts[2]);
        return new TableToken(deskId, step, nextOperateSeatIndex);
    }

}
